package macrochip.vison.com.gps.activity;

import android.animation.ObjectAnimator;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fh.lib.PlayInfo;
import com.photoalbum.activity.MediaActivity;
import com.vison.baselibrary.base.BaseFilterActivity;
import com.vison.baselibrary.helper.FunctionHelper;
import com.vison.baselibrary.listeners.AnalysisListener;
import com.vison.baselibrary.listeners.OnPhotographListener;
import com.vison.baselibrary.listeners.OnRecordListener;
import com.vison.baselibrary.listeners.OnSwitchVRModeListener;
import com.vison.baselibrary.model.MediaPixel;
import com.vison.baselibrary.model.SwitchType;
import com.vison.baselibrary.utils.LogUtils;
import com.vison.baselibrary.utils.ObjectUtils;
import com.vison.baselibrary.utils.SoundPoolUtil;
import com.vison.baselibrary.utils.ViewUtils;
import com.vison.baselibrary.widgets.CustomButton;
import com.vison.baselibrary.widgets.HeliwayRockerView;
import com.vison.baselibrary.widgets.RockerGroupView;
import com.vison.baselibrary.widgets.TrackView;

import java.lang.ref.WeakReference;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import macrochip.vison.com.gps.R;
import macrochip.vison.com.gps.application.MyApplication;
import macrochip.vison.com.gps.utils.AppUtils;
import macrochip.vison.com.gps.utils.GravityUtils;

import static com.fh.lib.PlayInfo.mirror;

/**
 * Created by dell on 2018/4/14.
 */

public class ControlActivity extends BaseFilterActivity implements AnalysisListener, RockerGroupView.OnRockerGroupTouchListener {
    @Bind(R.id.rocker_left)
    HeliwayRockerView leftRocker;
    @Bind(R.id.rocker_right)
    HeliwayRockerView rightRocker;
    @Bind(R.id.trackView)
    TrackView trackView;
    @Bind(R.id.imageBg)
    ImageView imageBg;
    @Bind(R.id.progressBar)
    ProgressBar progressBar;
    @Bind(R.id.speed)
    CustomButton speedBtn;
    @Bind(R.id.vr_mode)
    CustomButton vrBtn;
    @Bind(R.id.video)
    CustomButton videoBtn;
    @Bind(R.id.reverse)
    CustomButton revBtn;
    @Bind(R.id.fly_line)
    CustomButton flyLine;
    @Bind(R.id.video_time_button)
    Chronometer videoTimeButton;
    @Bind(R.id.layout_middle)
    LinearLayout middleLayout;
    @Bind(R.id.left_img)
    RelativeLayout leftImg;
    @Bind(R.id.right_img)
    RelativeLayout rightImg;
    @Bind(R.id.photo_anim)
    ImageView photoAnim;

    @Bind(R.id.mode_switch)
    CustomButton modeSwitchBtn;
    @Bind(R.id.gravity)
    CustomButton gravityBtn;
    @Bind(R.id.camera)
    CustomButton photoBtn;

    @Bind(R.id.text_return)
    TextView returnText;
    @Bind(R.id.text_on_off)
    TextView onOffText;
    @Bind(R.id.text_speed)
    TextView speedText;
    @Bind(R.id.text_gravity)
    TextView gravityText;
    @Bind(R.id.text_fly_line)
    TextView lineText;
    @Bind(R.id.text_switch)
    TextView switchText;
    @Bind(R.id.text_reverse)
    TextView reverseText;
    @Bind(R.id.text_vr)
    TextView vrText;
    @Bind(R.id.text_camera)
    TextView cameraText;
    @Bind(R.id.text_video)
    TextView videoText;
    @Bind(R.id.text_album)
    TextView albumText;
    @Bind(R.id.text_help)
    TextView helpText;
    @Bind(R.id.help_img)
    ImageView helpImg;
    @Bind(R.id.on_off)
    CustomButton onOffBtn;

    private long mPhotographLastTime;
    private SendControlThread mSendControlThread;
    private int mSpeedValue;                    // 速度 0，1，2
    private int mNoHeadValue;                   // 无头
    private int m360RollValue;                  // 翻滚
    private int mStopValue;                     // 急停
    private int mToFlyValue;                    // 起飞
    private int mToLandValue;                   // 下降
    private int mCalibrationValue;             // 校准

    private boolean trackMode = false;     // 轨迹模式
    private boolean vrMode = false;// vr模式
    private boolean isMenu = false;
    private boolean isControl = false;
    private boolean isNoHead = false;
    private boolean isLeft = false;
    private boolean isFine = true;
    private boolean isRoll = false;
    private boolean isSpeed = false;

    private GravityUtils gravityUtils;
    private int m360RollValueCount = 0;
    private static final int NOTIFY_TO_360RollClean = 5;
    private static final int NOTIFY_TO_PHOTO_ANIM = 7;

    private final MyHandler myHandler = new MyHandler(ControlActivity.this);

    @Override
    public void onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (view.getId() == R.id.rocker_right) {
                    rightImg.setVisibility(View.GONE);
                    rightRocker.setVisibility(View.VISIBLE);
                }
                if (view.getId() == R.id.rocker_left) {
                    leftImg.setVisibility(View.GONE);
                    leftRocker.setVisibility(View.VISIBLE);
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                if (view.getId() == R.id.rocker_right) {
                    rightImg.setVisibility(View.VISIBLE);
                }
                if (view.getId() == R.id.rocker_left) {
                    leftImg.setVisibility(View.VISIBLE);
                }
                break;

            case MotionEvent.ACTION_UP:
                if (view.getId() == R.id.rocker_right) {
                    rightImg.setVisibility(View.VISIBLE);
                }
                if (view.getId() == R.id.rocker_left) {
                    leftImg.setVisibility(View.VISIBLE);
                }
                break;
        }
    }


    private static class MyHandler extends Handler {
        private final WeakReference<ControlActivity> mActivity;

        public MyHandler(ControlActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ControlActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case SwitchType.NOTIFY_HIDE_BG:
                        if ((boolean) activity.imageBg.getTag()) {
                            activity.progressBar.setVisibility(View.GONE);
                            activity.imageBg.setTag(false);
                            ObjectAnimator anim = ObjectAnimator.ofFloat(activity.imageBg, "alpha", 1f, 0f);
                            anim.setDuration(1000);// 动画持续时间
                            anim.start();
                        }
                        break;

                    case SwitchType.NOTIFY_HIDE_CONTENT_VIEW:
                        activity.contentView.setVisibility(View.GONE);
                        break;

                    case SwitchType.NOTIFY_TO_STOP:
                        activity.mStopValue = 0;
                        break;

                    case NOTIFY_TO_360RollClean:
//                        activity.revBtn.setBackgroundResource(R.drawable.icon_rev_normal);
                        activity.isRoll = false;
                        activity.m360RollValue = 0;
                        break;

                    case NOTIFY_TO_PHOTO_ANIM:
                        activity.photoAnim.setVisibility(View.GONE);
                        ViewUtils.setEnabledByAlpha(activity.photoBtn, true);
                        break;
                }
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setShowPhotoAnimation(false);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);
        ButterKnife.bind(this);

        MyApplication.getInstance().setAnalysisListener(this);
        initView();
    }

    private void initView() {
        gravityUtils = new GravityUtils(getContext());
        videoBtn.setTag(false);
        setMJHideView(progressBar, imageBg);
        revBtn.setTag(true);
        imageBg.setTag(true);
        gravityBtn.setTag(false);
        flyLine.setTag(false);
        vrBtn.setTag(0);
        speedBtn.setTag(0);
        ViewUtils.setEnabledByAlpha(modeSwitchBtn, false);

        leftRocker.setMaxX(127);
        leftRocker.setMaxY(127);
        rightRocker.setMaxX(127);
        rightRocker.setMaxY(127);
        trackView.setMaxX(127);
        trackView.setMaxY(127);

        leftRocker.setOnRockerGroupTouchListener(this);
        rightRocker.setOnRockerGroupTouchListener(this);
    }

    private void helpView(boolean isShow) {
        if (isShow) {
            returnText.setText(R.string.text_return);
            onOffText.setText(R.string.text_on_off);
            speedText.setText(R.string.text_speed);
            gravityText.setText(R.string.text_gravity);
            lineText.setText(R.string.text_fly_line);
            switchText.setText(R.string.text_switch);
            reverseText.setText(R.string.text_reverse);
            vrText.setText(R.string.text_vr);
            cameraText.setText(R.string.text_photo);
            videoText.setText(R.string.text_video);
            albumText.setText(R.string.text_folder);
            helpText.setText(R.string.text_help);
            helpImg.setVisibility(View.VISIBLE);
            if (AppUtils.isZh(getContext())) {
                returnText.setTextSize(12);
                onOffText.setTextSize(12);
                speedText.setTextSize(12);
                gravityText.setTextSize(12);
                lineText.setTextSize(12);
                switchText.setTextSize(12);
                reverseText.setTextSize(12);
                vrText.setTextSize(12);
                cameraText.setTextSize(12);
                videoText.setTextSize(12);
                albumText.setTextSize(12);
                helpText.setTextSize(12);
            } else {
                returnText.setTextSize(12);
                onOffText.setTextSize(12);
                speedText.setTextSize(12);
                gravityText.setTextSize(12);
                lineText.setTextSize(12);
                switchText.setTextSize(10);
                reverseText.setTextSize(12);
                vrText.setTextSize(12);
                cameraText.setTextSize(12);
                videoText.setTextSize(12);
                albumText.setTextSize(12);
                helpText.setTextSize(12);
            }
        } else {
            returnText.setText("");
            onOffText.setText("");
            speedText.setText("");
            gravityText.setText("");
            lineText.setText("");
            switchText.setText("");
            reverseText.setText("");
            vrText.setText("");
            cameraText.setText("");
            videoText.setText("");
            albumText.setText("");
            helpText.setText("");
            helpImg.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.back, R.id.speed, R.id.vr_mode, R.id.video, R.id.camera, R.id.album, R.id.btn_home_help, R.id.help_img,
            R.id.on_off, R.id.fly_line, R.id.gravity, R.id.reverse, R.id.mode_switch})
    void OnClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_home_help:
                helpView(true);
                break;
            case R.id.help_img:
                helpView(false);
                break;
            case R.id.album:
                startActivity(MediaActivity.intent(getContext(), ControlActivity.class, MyApplication.SAVE_PATH));
                finish();
                break;
            case R.id.reverse:
                if (!mirror) {
                    MyApplication.getInstance().writeUDPCmd(new byte[]{0x02});
                } else {
                    MyApplication.getInstance().writeUDPCmd(new byte[]{0x01});
                }
                break;

            case R.id.mode_switch:
                isLeft = !isLeft;
                if (isLeft) {
                    modeSwitchBtn.setBackgroundResource(R.drawable.icon_mode2);
                } else {
                    modeSwitchBtn.setBackgroundResource(R.drawable.icon_mode1);
                }
                View middleView1 = middleLayout.getChildAt(0);
                View middleView2 = middleLayout.getChildAt(1);
                View middleView3 = middleLayout.getChildAt(2);

                middleLayout.removeAllViews();
                middleLayout.addView(middleView3);
                middleLayout.addView(middleView2);
                middleLayout.addView(middleView1);
                break;

            case R.id.gravity:
                rightRocker.showRocker(true);
                leftRocker.showRocker(true);
                rightImg.setVisibility(View.GONE);
                leftImg.setVisibility(View.GONE);
                boolean booGravity = !(boolean) gravityBtn.getTag();
                if (booGravity) {
                    if (gravityUtils.startGravityControl(leftRocker, rightRocker)) {
                        gravityBtn.setBackgroundResource(R.drawable.icon_gravity_press);
                        rightRocker.setCentre(false);
                        rightRocker.setManual(false);
                        rightRocker.setTouch(false);

                        leftRocker.setCentre(false);
                        leftRocker.setManual(false);
                        leftRocker.setTouch(false);
                        gravityBtn.setTag(booGravity);
                    } else {
                        showToast("device not support gravity");
                    }
                } else {
                    gravityBtn.setBackgroundResource(R.drawable.icon_gravity);
                    gravityUtils.closeGravityControl();
                    rightRocker.setCentre(true);
                    rightRocker.setManual(true);
                    rightRocker.setTouch(true);

                    leftRocker.setCentre(true);
                    leftRocker.setManual(true);
                    leftRocker.setTouch(true);
                    gravityBtn.setTag(booGravity);
                }
                break;

            case R.id.fly_line:
                trackMode = !(boolean) flyLine.getTag();
                flyLine.setTag(trackMode);
                if (trackMode) {
                    flyLine.setBackgroundResource(R.drawable.icon_line_press);
                    rightRocker.setVisibility(View.GONE);
                    leftRocker.setVisibility(View.GONE);
                    trackView.setVisibility(View.VISIBLE);
                    rightImg.setVisibility(View.GONE);
                    leftImg.setVisibility(View.GONE);
                    ViewUtils.setEnabledByAlpha(onOffBtn, false);
                    ViewUtils.setEnabledByAlpha(gravityBtn, false);
                } else {
                    flyLine.setBackgroundResource(R.drawable.icon_line);
                    leftRocker.setVisibility(View.VISIBLE);
                    rightRocker.setVisibility(View.VISIBLE);
                    trackView.setVisibility(View.GONE);
                    leftImg.setVisibility(View.VISIBLE);
                    rightImg.setVisibility(View.VISIBLE);
                    ViewUtils.setEnabledByAlpha(onOffBtn, true);
                    ViewUtils.setEnabledByAlpha(gravityBtn, true);
                }
                break;


            case R.id.speed:
                isSpeed = !isSpeed;
                if (isSpeed) {
                    mSpeedValue = 1;
                    speedBtn.setBackgroundResource(R.drawable.icon_speed_one);
                } else {
                    mSpeedValue = 2;
                    speedBtn.setBackgroundResource(R.drawable.icon_speed_two);
                }
                break;
            case R.id.on_off:
                isControl = !isControl;
                if (isControl) {
                    middleLayout.setVisibility(View.VISIBLE);
                    onOffBtn.setBackgroundResource(R.drawable.icon_on);
                    ViewUtils.setEnabledByAlpha(modeSwitchBtn, true);
                    // 开启数据发送线程
                    if (null == mSendControlThread) {
                        mSendControlThread = new SendControlThread();
                        mSendControlThread.start();
                    }
                } else {
                    middleLayout.setVisibility(View.GONE);
                    onOffBtn.setBackgroundResource(R.drawable.icon_off);
                    ViewUtils.setEnabledByAlpha(modeSwitchBtn, false);
                    // 关闭数据发送线程
                    if (null != mSendControlThread) {
                        mSendControlThread.cancel();
                        mSendControlThread = null;
                    }
                }
                break;

            case R.id.camera:
                photograph();
                break;

            case R.id.video:
                if (MyApplication.isDeviceConnected()) {
                    record(!(Boolean) videoBtn.getTag());
                }
                break;

            case R.id.vr_mode:
                FunctionHelper.switchVRMode(this, new OnSwitchVRModeListener() {
                    @Override
                    public void onOpen() {
                        vrMode = true;
//                        vrBtn.setBackgroundResource(R.drawable.icon_3d_btn_press);
                        myHandler.sendEmptyMessageDelayed(SwitchType.NOTIFY_HIDE_CONTENT_VIEW, 3000);

                    }

                    @Override
                    public void onClose() {
                        vrMode = false;
//                        vrBtn.setBackgroundResource(R.drawable.icon_3d_btn_normal);
                        myHandler.removeMessages(SwitchType.NOTIFY_HIDE_CONTENT_VIEW);
                        contentView.setVisibility(View.VISIBLE);
                    }
                });
                break;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP: {
                if (vrMode) {
                    contentView.setVisibility(View.VISIBLE);
                    myHandler.removeMessages(macrochip.vison.com.gps.mode.SwitchType.NOTIFY_HIDE_CONTENT_VIEW);
                    myHandler.sendEmptyMessageDelayed(macrochip.vison.com.gps.mode.SwitchType.NOTIFY_HIDE_CONTENT_VIEW, 5000);
                }
                break;
            }

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if ((boolean) videoBtn.getTag()){
            record(false);
        }

    }

    @Override
    public void onCbData(int type, byte[] data, int len) {
        super.onCbData(type, data, len);
        switch (type) {
            case SwitchType.CB_DATA_HIDE_BACKGROUND:
                myHandler.sendEmptyMessage(SwitchType.NOTIFY_HIDE_BG);
                break;
        }
    }

    /**
     * @param type
     * @param data
     */
    @Override
    public void data(int type, byte[] data) {
        switch (type) {

            case SwitchType.NOTIFY_TYPE_UPDATE_FLY_SEARCH_PHOTO:
                int mediaType = data[0];
                if (mediaType == 1) {
                    photograph();
                } else if (mediaType == 2) {
                    videoBtn.setTag(true);
                    if (videoTimeButton.getVisibility() == View.INVISIBLE) {
                        record(true);
                    }
                } else if (mediaType == 3) {
                    record(false);
                    videoBtn.setTag(false);
                }

                break;
        }
    }

    private void record(boolean val) {
        OnRecordListener onRecordListener=new OnRecordListener() {
            @Override
            public void onStart() {
                videoBtn.setTag(true);
                videoTimeButton.setVisibility(View.VISIBLE);
//                videoBtn.setBackgroundResource(R.drawable.icon_video_press);
                videoTimeButton.setBase(SystemClock.elapsedRealtime());//计时器清零
                videoTimeButton.start();
                ViewUtils.setEnabledByAlpha(photoBtn, false);
            }

            @Override
            public void onStop() {
                // 停止录像
                videoBtn.setTag(false);
//                videoBtn.setBackgroundResource(R.drawable.icon_video_normal);
                videoTimeButton.setVisibility(View.INVISIBLE);
                videoTimeButton.setBase(SystemClock.elapsedRealtime());//计时器清零
                videoTimeButton.stop();
                ViewUtils.setEnabledByAlpha(photoBtn, true);
            }
        };
        FunctionHelper.recordByGL(this,val, false,onRecordListener);
    }

    /**
     * 拍照
     */
    private void photograph() {
        LogUtils.d(MyApplication.SAVE_PATH);

        long time = System.currentTimeMillis();
        if (time - mPhotographLastTime > 500) {
            mPhotographLastTime = time;
            FunctionHelper.photograph(this, new OnPhotographListener() {
                @Override
                public void onSuccess() {
                    Toast.makeText(getContext(), "拍照", Toast.LENGTH_LONG).show();
                    SoundPoolUtil.play(getContext(), R.raw.mic_photograph);
                    photoAnim.setVisibility(View.VISIBLE);
                    AnimationDrawable animationDrawable = (AnimationDrawable) photoAnim.getBackground();
                    animationDrawable.setOneShot(true);
                    animationDrawable.start();
                    ViewUtils.setEnabledByAlpha(photoBtn, false);
                    myHandler.sendEmptyMessageDelayed(NOTIFY_TO_PHOTO_ANIM, 1000);
                }
            });
        }
    }

    /**
     * 飞控数据发送线程
     */
    private class SendControlThread extends Thread {
        private boolean isRun;

        public SendControlThread() {
            isRun = true;
        }

        public void run() {
            while (isRun) {
                byte[] data = new byte[11];
                data[0] = (byte) 0xFF;
                data[1] = (byte) 0x08;

                // 动力 0 - 255
                data[2] = (byte) 254;

                // 旋转
                data[3] = 0;

                // 前后
                data[4] = (byte) (leftRocker.getMaxY() - leftRocker.getYV());
                if (mSpeedValue == 1) {
                    if (data[4] > 64) {
                        data[4] -= 64;
                        data[4] *= 2;
                        data[4] /= 3;
                        data[4] = (byte) (64 + data[4]);
                    } else {
                        data[4] = (byte) (64 - data[4]);
                        data[4] *= 2;
                        data[4] /= 3;
                        data[4] = (byte) (64 - data[4]);
                    }
                }

                LogUtils.i("da", data[4]);
                // 左右
                if (trackMode) {
                    data[4] = (byte) (trackView.getMaxY() - trackView.getYV());
                    data[5] = (byte) trackView.getXV();
                } else {
                    data[5] = (byte) rightRocker.getXV();
                }

                if ((data[4] >= 96 || data[4] <= 32 || data[5] >= 96 || data[5] <= 32)
                        && (isRoll)) {
                    m360RollValue = 1;
                    m360RollValueCount++;
                    if (m360RollValueCount > 4) {
                        myHandler.sendEmptyMessageDelayed(NOTIFY_TO_360RollClean, 0);
                    }
                } else {
                    m360RollValueCount = 0;
                }

                // 旋转微调
                data[6] = 0x10;
                data[6] |= 0x80;
                data[6] = (byte) (data[6] | (mCalibrationValue << 6));

                // 前后微调
                if (isLeft) {
                    data[7] = 0x10;
                } else {
                    data[7] = 0x10;
                }

                // 左右微调
                data[8] = 0x10;

                data[9] = 0x02;
                data[10] = (byte) (0xFF - (byte) (data[1] + data[2] + data[3] +
                        data[4] + data[5] + data[6] + data[7] + data[8] + data[9]));
                MyApplication.getInstance().writeUDPCmd(data);
                String tmpStr = ObjectUtils.bytesToHexString(data);
                LogUtils.i("飞控" + tmpStr);
                try {
                    Thread.sleep(20);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        public void cancel() {
            isRun = false;
            this.interrupt();
        }

        public boolean getRun() {
            return isRun;
        }
    }
}
